//
//  PLPattern.h
//  Plankton
//
//  Created by Marc Schlichte on 15.06.09.
//  Copyright 2009 Framework Labs. All rights reserved.
//

#import <Foundation/Foundation.h>

@protocol PLMessageHandler, PLTimeoutHandler;

/// Patterns are used by clients of a platform to receive messages. When a message enters
/// a platform it will be checked against all currently registered patterns. The first pattern which
/// matches will have it's message handler invoked.
/// 
@interface PLPattern : NSObject
{
@private
	NSString				*receiver;
    id<PLMessageHandler>    messageHandler;
    id<PLTimeoutHandler>    timeoutHandler;
    NSTimeInterval          timeoutInterval;
    NSTimer                 *timeoutTimer;
    id                      userInfo;
}

+ (PLPattern *)patternAny;
+ (PLPattern *)patternWithPredicate:(NSPredicate *)predicate;
+ (PLPattern *)patternWithPredicateFormat:(NSString *)predicateFormat, ...;

- (PLPattern *)setMessageHandler:(id<PLMessageHandler>)handler;
- (PLPattern *)setMessageTarget:(id)target action:(SEL)action;

- (PLPattern *)setTimeoutHandler:(id<PLTimeoutHandler>)timeout after:(NSTimeInterval)interval;
- (PLPattern *)setTimeoutTarget:(id)target action:(SEL)action after:(NSTimeInterval)interval;

#if NS_BLOCKS_AVAILABLE
- (PLPattern *)setMessageBlock:(void (^)(id message, PLPattern *pattern))block;
- (PLPattern *)setTimeoutBlock:(void (^)(PLPattern *))block after:(NSTimeInterval)interval;
#endif

@property(nonatomic, retain) id userInfo;

- (BOOL)matches:(id)message;

@end


/// Defines the signature of the methods which get called when a pattern maches a message.
///
@protocol PLMessageHandler <NSObject>

- (void)handleMessage:(id)message forPattern:(PLPattern *)pattern;

@end

/// When a pattern is added to a platform it is possible to specify a timeout interval
/// after which the method defined in this protocol is called.
///
@protocol PLTimeoutHandler <NSObject>

- (void)handleTimeoutForPattern:(PLPattern *)pattern;

@end

